//
//  PageOneViewController.m
//  WeatherForecastDemo
//
//  Created by lizhiwei on 13-1-2.
//  Copyright (c) 2013年 lizhiwei. All rights reserved.
//

#import "PageOneViewController.h"
#import "JSON.h"
#import "SetCity1ViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "DayView.h"
#import "DayWeather.h"
#import "AppDelegate.h"
#import "TKAlertCenter.h"
#import "RCAlertViewUtil.h"

#define WEATHER_DAY_COUNT 3
#define TIMER_INTERVAL 30	//只显示分，定时器不用更新频繁
#define TODAY_VIEW_ORIGIN CGPointMake(6, 343)
#define VIEW_DISTANCE 104
#define TOMORROW_VIEW_ORIGIN CGPointMake(164, 343)
#define DAY_AFTER_TOMO_ORIGIN CGPointMake(322, 343)

@interface PageOneViewController ()
- (void)updateTime;
@end

@implementation PageOneViewController
@synthesize activityIndicator;
@synthesize lbDate;
@synthesize lbWeek;
@synthesize lbWeather1;
@synthesize lbtemp1;
@synthesize lbCityName;
@synthesize hourUpView;
@synthesize hourDownView;
@synthesize minuteUpView;
@synthesize minuteDownView;
@synthesize todayWeatherView;
@synthesize lbxc;
@synthesize progress;
//@synthesize CityCode;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    timer = [NSTimer scheduledTimerWithTimeInterval:TIMER_INTERVAL target:self
										   selector:@selector(updateTime) userInfo:nil repeats:YES];
	[timer fire];
    //[activityIndicator startAnimating];
    [self setWeatherInfoRequest];
}

-(void)setWeatherInfoRequest//向中国气象局平台发送深圳天气预报请求报文
{
    NSString *strUrl=[NSString stringWithFormat:@"http://m.weather.com.cn/data/%@.html",[AppDelegate app].CityCode];
    NSString *strUrlEncod = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//字符串编码转换
    NSURL *myurl = [NSURL URLWithString:strUrlEncod];
    NSLog(@"请求报文为:%@",strUrl);
    requestWeather=[ASIHTTPRequest requestWithURL:myurl];
    requestWeather.tag=1001;
    
    [requestWeather setDelegate:self];
    [requestWeather setDidFailSelector:@selector(ResponseFail:)];
    [requestWeather setDidFinishSelector:@selector(ResonseSuccess:)];
    [requestWeather startAsynchronous];
    
    showProgress = YES;
    if (showProgress) 
    {
        progress= [[MBProgressHUD alloc]initWithView:self.view];
        [self.view addSubview:progress];
        [self.view bringSubviewToFront:progress];
        progress.labelText = @"更新中...";
        [progress show:YES];
        showProgress = NO;
    };
}

- (void)ResonseSuccess:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    
    NSString *responseString = [request responseString];
    NSLog(@"responseString %@",responseString);
    if (responseString.length==0) {
        [self justShowMessage:@"返回的数据为空!" title:@"注意"];
        return;
    }
    NSMutableDictionary *dictResponse=[responseString JSONValue];
    NSLog(@"dictResponse  %@",dictResponse);
    
    NSMutableDictionary *jsonoSubObj = [dictResponse objectForKey:@"weatherinfo"];
    
    NSString * date = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"date_y"]];
    NSString * week = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"week"]];
    NSString * weather1 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"weather1"]];
    NSString * temp1 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"temp1"]];
    NSString * city = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"city"]];
    //洗车指数
    NSString * xc = [[NSString alloc] initWithFormat:@"洗车:%@",[jsonoSubObj objectForKey:@"index_xc"]];
    lbxc.text = xc;
    lbDate.text = date;
    lbtemp1.text = temp1;
    lbWeather1.text = weather1;
    lbWeek.text = week;
    lbCityName.text = city;
    
    
    NSString * imgname = [[NSString alloc] initWithFormat:@"%@",
                          [jsonoSubObj objectForKey:@"img1"]];
    NSString *pictureName = imgname;
	pictureName = [NSString stringWithFormat:@"a_%@.png", pictureName];
	[todayWeatherView setImage:[UIImage imageNamed:pictureName]];
    
    /******---未来三天的天气数据---******/
    NSString *temp2 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"temp2"]];
    NSString *weather2 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"weather2"]];
    NSLog(@"=======%@",temp2);
    
    if (temp2.length == 0)
    {
        [[TKAlertCenter defaultCenter] postAlertWithMessage:@"获取天气信息失败!"];
        return;
    }
    
    NSString *temp3 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"temp3"]];
    NSString *weather3 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"weather3"]];
    
    NSString *temp4 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"temp4"]];
    NSString *weather4 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"weather4"]];
    
    NSString *wind2 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"wind2"]];
    NSString *wind3 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"wind3"]];
    NSString *wind4 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"wind4"]];
    
    NSString * img2 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"img2"]];
    NSString * img3 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"img3"]];
    NSString * img4 = [[NSString alloc] initWithFormat:@"%@",[jsonoSubObj objectForKey:@"img4"]];
    
    //需要我们初始化一个空间大小，用dictionaryWithCapacity
    WeatherInfo = [NSMutableDictionary dictionaryWithCapacity:15];
    //这里我们给的空间大小是15,当添加的数据超过的时候，它的空间大小会自动扩大
    
    //添加数据，注意：id key是成对出现的
    
    NSString * week2;
    NSString * week3;
    NSString * week4;
    if ([week isEqualToString:@"星期一"])
    {
        week2 = @"星期二";
        week3 = @"星期三";
        week4 = @"星期四";
    }
    else if([week isEqualToString:@"星期二"])
    {
        week2 = @"星期三";
        week3 = @"星期四";
        week4 = @"星期五";
    }
    else if([week isEqualToString:@"星期三"])
    {
        week2 = @"星期四";
        week3 = @"星期五";
        week4 = @"星期六";
    }
    else if([week isEqualToString:@"星期四"])
    {
        week2 = @"星期五";
        week3 = @"星期六";
        week4 = @"星期日";
    }
    else if([week isEqualToString:@"星期五"])
    {
        week2 = @"星期六";
        week3 = @"星期日";
        week4 = @"星期一";
    }
    else if([week isEqualToString:@"星期六"])
    {
        week2 = @"星期日";
        week3 = @"星期一";
        week4 = @"星期二";
    }
    else if([week isEqualToString:@"星期日"]||[week isEqualToString:@"星期天"])
    {
        week2 = @"星期一";
        week3 = @"星期二";
        week4 = @"星期三";
    }
    
    [WeatherInfo setObject:temp2 forKey:@"temp2"];
    [WeatherInfo setObject:temp3 forKey:@"temp3"];
    [WeatherInfo setObject:temp4 forKey:@"temp4"];
    [WeatherInfo setObject:weather2 forKey:@"weather2"];
    [WeatherInfo setObject:weather3 forKey:@"weather3"];
    [WeatherInfo setObject:weather4 forKey:@"weather4"];
    [WeatherInfo setObject:wind2 forKey:@"wind2"];
    [WeatherInfo setObject:wind3 forKey:@"wind3"];
    [WeatherInfo setObject:wind4 forKey:@"wind4"];
    [WeatherInfo setObject:week2 forKey:@"week2"];
    [WeatherInfo setObject:week3 forKey:@"week3"];
    [WeatherInfo setObject:week4 forKey:@"week4"];
    [WeatherInfo setObject:img2 forKey:@"img2"];
    [WeatherInfo setObject:img3 forKey:@"img3"];
    [WeatherInfo setObject:img4 forKey:@"img4"];
    
    if ([daysViews count] == 0)
    {
		daysViews = [[NSMutableArray alloc] initWithCapacity:WEATHER_DAY_COUNT];
		DayView *dayView;
		for (int i = 0; i < WEATHER_DAY_COUNT; i++)
        {
			dayView = [DayView alloc];
			NSArray *nib=[[NSBundle mainBundle] loadNibNamed:@"DayView" owner:self options:nil];
			dayView = [nib objectAtIndex:0];
			
			CGRect rect = dayView.frame;
			rect.origin = CGPointMake(TODAY_VIEW_ORIGIN.x + VIEW_DISTANCE * i, TODAY_VIEW_ORIGIN.y);
			dayView.frame = rect;
            [dayView setUpInfo:WeatherInfo:i];
            //[dayView TestInof];
			[self.view addSubview:dayView];
			[daysViews addObject:dayView];
			[dayView release];
		}
	}
    /******---未来三天的天气数据---******/
    [outString release];
    return;
}

- (void)ResponseFail:(ASIHTTPRequest *)request
{
    if (!showProgress)
    {
        [progress removeFromSuperview];
        progress = nil;
    }
    NSLog(@"服务器连接失败!");
    [[TKAlertCenter defaultCenter] postAlertWithMessage:@"天气信息获取失败,服务器连接失败!"];
    return;
}

/*
 * 内部做个定时器，定时更新时间 日期 天气实况
 */
- (void)updateTime{
	//更新时间 还有am pm
	NSDate *today = [NSDate date];
	NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
	//[dateFormatter setTimeStyle:kCFDateFormatterShortStyle];
    [dateFormatter setDateFormat:@"HH:mm"];
	//[dateFormatter setDateFormat:@"HH:mm:SS"];
	NSString *currentTime = [dateFormatter stringFromDate:today];
	[dateFormatter release];
    //	DebugLog(@"User's current time in their preference format:%@",currentTime);
	
	NSArray *timeArray = [currentTime componentsSeparatedByString:@":"];
	// 获得小时各位图片索引
	NSUInteger hour = [[timeArray objectAtIndex:0] intValue];
	NSString *imageName;
	imageName = [NSString stringWithFormat:@"NUMBER_%d.png", hour%10];
	[hourDownView setImage:[UIImage imageNamed:imageName]];
	
	imageName = [NSString stringWithFormat:@"NUMBER_%d.png", hour/10];
	[hourUpView setImage:[UIImage imageNamed:imageName]];
	
	// 获得分钟各位图片索引
	NSUInteger minute = [[timeArray objectAtIndex:1] intValue];
	imageName = [NSString stringWithFormat:@"NUMBER_%d.png", minute%10];
	[minuteDownView setImage:[UIImage imageNamed:imageName]];
	
	imageName = [NSString stringWithFormat:@"NUMBER_%d.png", minute/10];
	[minuteUpView setImage:[UIImage imageNamed:imageName]];
	
	// todo:
	// 更新日期 24小时
	// 更新天气实况 3小时
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    [lbxc release];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

-(void)dealloc
{
    requestWeather.delegate=nil;
    [activityIndicator release];
    [todayWeatherView release];
    [progress release];
    progress = nil;
    [super dealloc];
}

@end
